//
//  NSString+Category.m



#import "NSString+Category.h"
#import "LCMD5Tool.h"
#import "NSDictionary+safe.h"

#define MD5Str  @"l]Ybbrj_ZnFz5~9VB7)Gq7[0HGCY]oq{1*I]Eji_e[(~qVRYB#axu+r6IDzeE0*EvX2&BCWt~QmXZc=="
//--------------------------------  密码后缀  ------------------------------
#define PasswordSuffix @"cnbbx"
#define FONTB(size) [UIFont boldSystemFontOfSize:size]

@implementation NSString (Category)

/* 获取ascll值 */
- (NSInteger)ascllIntValue{
    NSInteger intValue = 0;
    for (int i=0; i<self.length; i++) {
        intValue += [self characterAtIndex:i];
    }
    return intValue;
}

/* 获取随机的uuid */
+ (NSString *)uuid{
    CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
    CFStringRef strUuid = CFUUIDCreateString(kCFAllocatorDefault,uuid);
    NSString * str = [NSString stringWithString:(__bridge NSString *)strUuid];
    CFRelease(strUuid);
    CFRelease(uuid);
    return  str;
}

/* 转成密码 */
- (NSString *)pwdString{
    NSString *password = [LCMD5Tool MD5ForLower32Bate:[NSString stringWithFormat:@"%@%@", self, PasswordSuffix]];
    return password;
}

// 获取文档目录路径
+ (NSString *)getDocumentPath{
    NSArray *userPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    return [userPaths objectAtIndex:0];
}

// 获取cache目录路径
+ (NSString *)getCachePath{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    return [paths objectAtIndex:0];
}

// 获取文件在cache目录的路径
+ (NSString *)getFileCachePath:(NSString *)fileName{
    if (nil == fileName){
        return nil;
    }
    NSString *cacheDirectory = [self getCachePath];
    NSString *fileFullPath = [cacheDirectory stringByAppendingPathComponent:fileName];
    return fileFullPath;
}

/* 是不是文件路径 */
- (BOOL)isExistFilePath{
    if ([self isEmpty]){
        return NO;
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    return [fileManager fileExistsAtPath:self];
}

/* 是不是空字符串 */
- (BOOL)isEmpty{
    return self == nil || self.length == 0;
}

/* 转字典 */
- (NSDictionary *)toDict{
    NSData *jsonData = [self dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    return dict;
}

// 在cache目录下创建一个目录
+ (BOOL)createDirectoryAtCache:(NSString *)dirName{
    if (nil == dirName){
        return NO;
    }
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *dirPath = [self getFileCachePath:dirName];
    if ([fileManager fileExistsAtPath:dirPath]){
        return YES;
    }
    BOOL succ = [fileManager createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil];
    return succ;
}


+(BOOL)validateEMSnumber:(NSString *)EMSnumber
{
    BOOL flag;
    if (EMSnumber.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString * reg = @"^[0-9a-zA-Z]{10,}$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",reg];
    return [identityCardPredicate evaluateWithObject:EMSnumber];
}


- (NSString *)removeSpaceAndNewline:(NSString *)str
{
    NSString *temp = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    NSString *text = [temp stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet ]];
    return text;
}

// 给定字符串根据指定的个数进行分组，每一组用空格分隔
- (NSString *)showRuleBank {
    NSString *string = self;
    NSString *str = [string stringByReplacingOccurrencesOfString:@" " withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, string.length)];
    // 根据长度计算分组的个数
    NSInteger groupCount = (NSInteger)ceilf((CGFloat)str.length /4);
    NSMutableArray *components = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < groupCount; i++) {
        if (i*4 + 4 > str.length) {
            [components addObject:[str substringFromIndex:i*4]];
        } else {
            NSString * secureStr = [str substringWithRange:NSMakeRange(i*4, 4)];
            [components addObject:secureStr];
        }
    }
    for (int i =1; i<components.count-1; i++) {
        [components replaceObjectAtIndex:i withObject:@"****"];
    }
    NSString *groupedString = [components componentsJoinedByString:@" "];
    return groupedString;
}




- (CGSize)sizeWithFont:(UIFont *)font{
    CGSize result = [self sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil]];
    result.height = ceilf(result.height);
    result.width = ceilf(result.width);
    return result;
}

- (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size{
    CGSize result = [self boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:[NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName, nil] context:nil].size;
    result.height = ceilf(result.height);
    result.width = ceilf(result.width);
    return result;
}

/* 隐藏手机号中间四位 */
- (NSString *)hideFourPhone{
    if(self.length >= 11){
        return [self stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    }
    return self;
}

- (NSString *)htmlAdaptation{
    NSString *result = [NSString stringWithFormat:@"<%@ %@",@"img",@"style='display: block; max-width: 100%;'"];
    NSString *newHtml = [self stringByReplacingOccurrencesOfString:@"<img" withString:result];
    NSString *htmlStr = [NSString stringWithFormat:@"<html><head><meta http-equiv=\'Content-Type\' content=\'text/html; charset=utf-8\'/><meta content=\'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0;\' name=\'viewport\' /><meta name=\'apple-mobile-web-app-capable\' content=\'yes\'><meta name=\'apple-mobile-web-app-status-bar-style\' content=\'black\'><link rel=\'stylesheet\' type=\'text/css\' /><style type=\'text/css\'> .color{color:#576b95;}</style></head><body><div id=\'content\'>%@</div>", newHtml];
    return htmlStr;
}

- (NSAttributedString *)addPrefix:(NSString *)prefix sSize:(CGFloat)sSize bSize:(CGFloat)bSize color:(UIColor *)color{
    NSString *allString = [NSString stringWithFormat:@"%@%@",prefix, self];
    NSRange allRange = NSMakeRange(0,allString.length);
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:allString];
    [attrString addAttributes:@{NSFontAttributeName:FONTB(bSize), NSForegroundColorAttributeName:color} range:allRange];
    [attrString addAttribute:NSFontAttributeName value:FONTB(sSize) range:NSMakeRange(0,prefix.length)];
    return attrString;
}

/* 添加后缀 */
- (NSAttributedString *)addSuffix:(NSString *)prefix sSize:(CGFloat)sSize bSize:(CGFloat)bSize color:(UIColor *)color{
    NSString *allString = [NSString stringWithFormat:@"%@%@",self, prefix];
    NSRange allRange = NSMakeRange(0,allString.length);
    NSMutableAttributedString *attrString = [[NSMutableAttributedString alloc] initWithString:allString];
    [attrString addAttributes:@{NSFontAttributeName:FONTB(bSize), NSForegroundColorAttributeName:color} range:allRange];
    NSRange rg = [allString rangeOfString:prefix];
    [attrString addAttribute:NSFontAttributeName value:FONTB(sSize) range:rg];
    return attrString;
}


+ (NSString *)limitFloatValue:(CGFloat)value{
    if (fmodf(value, 1)==0) {//0
        return [NSString stringWithFormat:@"%.0f",value];
    } else if (fmodf(value*10, 1)==0) {//1
        return [NSString stringWithFormat:@"%.1f",value];
    }else {//2
        return [NSString stringWithFormat:@"%.2f",value];
    }
}

- (NSAttributedString *)htmlString{
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[self dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    return attrStr;
}


#pragma mark --- 将时间转换成时间戳
- (NSString *)getTimestampFromFormatter:(NSDateFormatter *)formatter{
    NSDate *timeData = [formatter dateFromString:self];
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[timeData timeIntervalSince1970]];
    return timeSp;
}

#pragma mark ---- 将时间戳转换成时间
- (NSString *)getTimeFromFormatter:(NSDateFormatter *)formatter{
    //将对象类型的时间转换为NSDate类型
    NSInteger time = [self integerValue];
    NSDate * myDate=[NSDate dateWithTimeIntervalSince1970:time];
    //将时间转换为字符串
    NSString *timeStr=[formatter stringFromDate:myDate];
    return timeStr;
}

#pragma mark - 秒转换成分秒
+ (NSString *)timeFormatted:(NSInteger)totalSeconds
{

    NSInteger seconds = totalSeconds % 60;
    NSInteger minutes = (totalSeconds / 60) % 60;

    return [NSString stringWithFormat:@"%02ld:%02ld", minutes, seconds];
}

/* 给url后面添加参数 */
- (NSString *)appendPamrWithDict:(NSDictionary *)dict{
    NSMutableString *mtbStr = [NSMutableString stringWithString:self];
    BOOL hasPrm =  [mtbStr containsString:@"?"];
    if(!hasPrm){
        [mtbStr appendString:@"?"];
    }
    [dict.allKeys enumerateObjectsUsingBlock:^(NSString *_Nonnull key, NSUInteger idx, BOOL * _Nonnull stop) {
        id value = [dict safeObjectForKey:key];
        if(value){
            [mtbStr appendFormat:@"&%@=%@", key, value];
        }
    }];
    return mtbStr;
}

+ (NSString *)timeStrWithSecend:(NSInteger)secend{
    NSInteger h = secend/3600;
    NSInteger m = secend%3600/60;
    NSInteger s = secend%60;
    return [NSString stringWithFormat:@"%02ld:%02ld:%02ld", h, m, s];
}


/* 字符串是否空 */
+ (BOOL)isBlankString:(NSString *)aStr {
    if (!aStr) {
        return YES;
    }
    if ([aStr isKindOfClass:[NSNull class]]) {
        return YES;
    }
    NSCharacterSet *set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
    NSString *trimmedStr = [aStr stringByTrimmingCharactersInSet:set];
    if (!trimmedStr.length) {
        return YES;
    }
    return NO;
}

/*获取某个字符串或者汉字的首字母. */
+ (NSString *)firstCharactorWithString:(NSString *)string
{
    NSMutableString *str = [NSMutableString stringWithString:string];
    CFStringTransform((CFMutableStringRef) str, NULL, kCFStringTransformMandarinLatin, NO);
    CFStringTransform((CFMutableStringRef)str, NULL, kCFStringTransformStripDiacritics, NO);
    NSString *pinYin = [str capitalizedString];
    return [pinYin substringToIndex:1];
}

/* 将JSON串转化为字典或者数组 */
+ (id)toArrayOrNSDictionary:(NSString *)jsonData{
    if (jsonData != nil) {
        NSData* data = [jsonData dataUsingEncoding:NSUTF8StringEncoding];
        id jsonObject = [NSJSONSerialization JSONObjectWithData:data
                                                        options:NSJSONReadingAllowFragments
                                                          error:nil];
        if (jsonObject != nil){
            return jsonObject;
        }else{
            // 解析错误
            return nil;
        }
    }
    return nil;
}
// 返回加密后的字符串
+ (NSString *)encodeWithParams:(id)params apiName:(NSString *)apiName
{
   NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:params];
   [dic setObject:apiName forKey:@"service"];
   
   NSArray *sortArray = [[dic allKeys] sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2)
                         {
                            return [[obj1 lowercaseString] compare:[obj2 lowercaseString]];
                         }];
   
//   NSLog(@"sortArray ==============  %@",sortArray);

   NSMutableArray *valueArr = [NSMutableArray array];
   for (NSString *sortString in sortArray) {
      [valueArr addObject:[dic objectForKey:sortString]];
   }
   
   NSMutableString *valueStr = [NSMutableString string];
   
   for (id value in valueArr)
   {
      if ([value isKindOfClass:[NSString class]])
      {
         [valueStr appendString:value];
      }
      else
      {
         [valueStr appendString:[value stringValue]];
      }
   }
   [valueStr appendString:MD5Str];
   
   for (int i = 0; i < 3; i++)
   {
       
       
      valueStr = [[LCMD5Tool MD5ForLower32Bate:valueStr] mutableCopy];
   }
   
   return valueStr ;
}
@end
